package com.david.controller.api;

import com.david.entity.Message;
import com.david.model.api.ExcelData;
import com.david.model.api.PageOf;
import com.david.model.api.Response;
import com.david.service.MessageService;
import com.david.utils.DateTimeUtils;
import com.david.utils.ExportExcelUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    MessageService messageService;

    @GetMapping("findByType")
    @ApiOperation(value = "留言列表", notes = "留言列表", tags = "message")
    public Response<Object> findByType(Integer type, Integer page, Integer pageSize) {
        Response<Object> result = new Response<>();
        result.data = messageService.findByType(type, page, pageSize);
        return result;
    }

    @GetMapping("findById")
    @ApiOperation(value = "findById", notes = "findById", tags = "message")
    public Message findById(Integer id) {
        return messageService.findById(id);
    }

    @GetMapping("insert")
    @ApiOperation(value = "insert", notes = "insert", tags = "message")
    public int insert(Message message) {
        return messageService.insert(message);
    }

    @GetMapping("/excels")
    @ApiOperation(value = "excels", notes = "使用该接口批量导出历史记录", tags = "WaybillHistory")
    public void excel(HttpServletResponse response, Integer type) throws Exception {
        if (null == type) {
            type = 0;
        }
        PageOf<Message> byType = messageService.findByType(type, 1, 100000);
        if (null == byType && byType.Data == null) {
            return;
        }

        ExcelData<Message> excelData = new ExcelData<>();
        excelData.setName(DateTimeUtils.GetPSTDateTime() + ".xlsx");
        excelData.setTitles(Arrays.asList(new String[]{
                "id",
                "姓名",
                "手机",
                "内容",
                "创建日期",
                "类型"
        }));
        excelData.setRows(byType.Data);
        Random random = new Random();
        ExportExcelUtils.exportExcel(response, "导出文件.xlsx", excelData);
    }
}
